import { Component } from "@angular/core";
import { NavController,NavParams } from "ionic-angular";
import { HttpClient } from '@angular/common/http'
import { NativeStorage } from '@ionic-native/native-storage';
import { TranslateService } from '@ngx-translate/core';
@Component({
  selector: 'page-search',
  templateUrl: 'city.html',
})
export class CityPage {
    callback:any;
    city: string;
    list:Array<any>;
    param:string;

    constructor(
      private navParams:NavParams,
      private navCtl:NavController,
      private storage:NativeStorage,
      private http:HttpClient,
      private translate: TranslateService,
    ){
      this.callback = this.navParams.get("callback");
      translate.setDefaultLang('en');
    }
    ionViewDidLoad(){
      this.storage.getItem('latlng').then((res)=>{
        this.http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng='+res[0]+','+res[1]+'&key=AIzaSyDMIoz9tJaVEjoD6fbONMiBAIOMwWdL-Dg&result_type=locality').subscribe(resp=>{
          this.city = resp['results'][0]['address_components'][0]['long_name']
        })
      })
      this.storage.getItem('city').then((res)=>{
        this.list = res
      })
    }
    ionViewDidEnter(){
      this.storage.getItem('lang').then(res=>{
          this.translate.use(res)
      })
    }
    choose(item:string){
      this.param = item;
    }
    goback(){
      if(event['keyCode']==13){
        this.jump();
      }
    }
    jump(){
      if(this.param){
        this.storage.getItem('city').then((res)=>{
          if(res.indexOf(this.param)==-1){
            res.push(this.param)
          }
          this.storage.setItem('city',res).then(resp=>{
            this.callback(this.param).then(()=>{
              this.navCtl.pop();
            });
          })
        }).catch((res)=>{
          this.storage.setItem('city',[this.param]).then(resp=>{
            this.callback(this.param).then(()=>{
              this.navCtl.pop();
            });
          })
        })
      }
    }
    clear(){
      this.storage.clear().then(()=>{
        this.list = [];
      });
    }
}